package com.spring.pay.weixin.controller.weixin;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.spring.pay.weixin.config.WeiXinConfig;
import com.spring.pay.weixin.handler.ResponseHandler;
import com.spring.pay.weixin.service.IWeiXinService;
import com.spring.pay.weixin.util.XMLUtil;

@RestController
@RequestMapping("/weixin")
public class WeiXinApiController{
	private Logger LOGGER = Logger.getLogger(WeiXinApiController.class);
	
	@Autowired
	private IWeiXinService weiXinServiceImpl;

	/**
	 * 微信回调
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("/receiveNotify")
	public void receiveNotify(HttpServletRequest request, HttpServletResponse response) {
		
		LOGGER.debug(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 微信来回调啦...");
		
		try {
			
			ResponseHandler resHandler = new ResponseHandler(request, response);
			//商户号的key
			resHandler.setKey(WeiXinConfig.PARTNER_KEY);
			
			String returnCode = weiXinServiceImpl.receiveNotify(resHandler);
			
			Map<String, String> map = new HashMap<String,String>();
			map.put("return_code", returnCode);
			
			String params = XMLUtil.mapToXml(map);
			
			resHandler.sendToCFT(params);
		} catch (IOException e) {
			LOGGER.error("微信回调返回系统异常！" + e);
		}
	}
	
	
}
